﻿using BusinessEntity;
using BusinessEntity.xmglQuerryEntity;
using BusinessRepository;
using BusinessRule.Organization;
using learun.util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule
{
    public class ProZhaoBiaoRule
    {
        #region 导入
        public async static Task<bool> GetImportTBRList(List<CProTB> listtbr)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                for (int i = 0; i < listtbr.Count; i++)
                {
                    //先删除
                    await irp.DeleteAny<CProTB>(new { tbdw = listtbr[i].tbdw, zbid = listtbr[i].zbid });
                    //在新增
                    await irp.Insert(listtbr[i]);
                }
                return true;

            });
        }
        #endregion

        #region 导出
        /// <summary>
        /// 用户列表（导出Excel）
        /// </summary>
        /// <returns></returns>
        public static async Task<MemoryStream> GetExportList(List<string> ids, List<ColumnModel> cols)
        {
            //List<string> ids = new List<string>();
            //List<ColumnModel> cols = new List<ColumnModel>();

            //取出数据源
            DataTable exportTable = await GetExportList(ids);
            //设置导出格式
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.Title = "招标信息";
            excelconfig.TitleFont = "微软雅黑";
            excelconfig.TitlePoint = 25;
            //excelconfig.HeadPoint = 12;
            excelconfig.FileName = "招标信息.xls";
            excelconfig.IsAllSizeColumn = true;
            //每一列的设置,没有设置的列信息，系统将按datatable中的列名导出
            excelconfig.ColumnEntity = new List<ColumnModel>();
            for (int i = 0; i < cols.Count; i++)
            {
                excelconfig.ColumnEntity.Add(new ColumnModel() { Column = cols[i].Column, ExcelColumn = cols[i].ExcelColumn });
            }

            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_account", ExcelColumn = "账户" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_realname", ExcelColumn = "姓名" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_gender", ExcelColumn = "性别" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_birthday", ExcelColumn = "生日" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_mobile", ExcelColumn = "手机", Background = Color.Red });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_telephone", ExcelColumn = "电话", Background = Color.Red });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_wechat", ExcelColumn = "微信" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_organize", ExcelColumn = "公司" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_department", ExcelColumn = "部门" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_description", ExcelColumn = "说明" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_createdate", ExcelColumn = "创建日期" });
            //excelconfig.ColumnEntity.Add(new ColumnModel() { Column = "f_createusername", ExcelColumn = "创建人" });
            //
            return ExcelHelper.ExportMemoryStream(exportTable, excelconfig);
        }

        public async static Task<DataTable> GetExportList(List<string> ids)
        {
            //throw new NotImplementedException();
            string yids = string.Join("','", ids);
            yids = "'" + yids + "'";
            string strsql = "select * from View_ProZBLists where id in (" + yids + ")";
            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }

        #endregion

        #region 查询
        //查询列表
        //public static async Task<(DataTable, int)> GetZBIndexListD(ProZhaoBiaoQuerry querry, string strdepids)//string uid
        //{
        //    string str = "";
        //    if (!(string.IsNullOrEmpty(querry.Jsdw)))
        //    {
        //        str = str + " and BuildUnit like '%" + querry.Jsdw + "%'";
        //    }
        //    if (!(string.IsNullOrEmpty(querry.Xmmc)))
        //    {
        //        str = str + " and xmmc like '%" + querry.Xmmc + "%'";
        //    }
        //    if (!(string.IsNullOrEmpty(querry.Xmfl)))
        //    {
        //        str = str + " and xmflname = '" + querry.Xmfl + "'";
        //    }

        //    if (!(string.IsNullOrEmpty(querry.cgfs)))
        //    {
        //        str = str + " and cgfs = '" + querry.cgfs + "'";
        //    }
        //    if (!(string.IsNullOrEmpty(querry.dxmc)))
        //    {
        //        str = str + " and dxmc = '" + querry.dxmc + "'";
        //    }
        //    if (!(string.IsNullOrEmpty(querry.cgmc)))
        //    {
        //        str = str + " and cgmc = '" + querry.cgmc + "'";
        //    }

        //    if (!(string.IsNullOrEmpty(querry.Begindate.ToString())))
        //    {
        //        str = str + " and kbrq >= ''" + querry.Begindate + "''";
        //    }
        //    if (!(string.IsNullOrEmpty(querry.Enddate.ToString())))
        //    {
        //        str = str + " and kbrq <= ''" + querry.Enddate + "''";
        //    }
        //    if (!(string.IsNullOrEmpty(querry.Status)))
        //    {
        //        str = str + " and spstatus = ''" + querry.Status + "''";
        //    }

        //    //await UserRule.GetUserDepid(uid)
        //    string sql = "select * from View_ProZBLists where departid in " + strdepids + str.Replace("''", "'");
        //    bool isAsc = true;
        //    if (querry.sort != "Asc" && querry.sort != "asc")
        //    {
        //        isAsc = false;
        //    }
        //    if (string.IsNullOrEmpty(querry.column))
        //    {
        //        querry.column = "id";
        //    }
        //    return await new RepositoryFactory().BaseRepository().FindTable(sql, null, querry.column, isAsc, querry.size, querry.current);

        //}

        public static async Task<(IEnumerable<dynamic>, int)> GetZBIndexList(ProZhaoBiaoQuerry querry, string strdepids)//string uid
        {
            string str = "";
            if (!(string.IsNullOrEmpty(querry.Jsdw)))
            {
                str = str + " and BuildUnit like '%" + querry.Jsdw + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.Xmmc)))
            {
                str = str + " and xmmc like '%" + querry.Xmmc + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.Xmfl)))
            {
                str = str + " and xmflname = '" + querry.Xmfl + "'";
            }

            if (!(string.IsNullOrEmpty(querry.cgfs)))
            {
                str = str + " and cgfs = '" + querry.cgfs + "'";
            }
            if (!(string.IsNullOrEmpty(querry.dxmc)))
            {
                str = str + " and dxmc like '%" + querry.dxmc + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.cgmc)))
            {
                str = str + " and cgmc like '%" + querry.cgmc + "%'";
            }

            if (!(string.IsNullOrEmpty(querry.Begindate.ToString())))
            {
                str = str + " and kbrq >= '" + querry.Begindate + "'";
            }
            if (!(string.IsNullOrEmpty(querry.Enddate.ToString())))
            {
                str = str + " and kbrq <= '" + querry.Enddate + "'";
            }
            if (!(string.IsNullOrEmpty(querry.Status)))
            {
                str = str + " and spstatus = '" + querry.Status + "'";
            }

            if (!(string.IsNullOrEmpty(querry.zbzt)))
            {
                str = str + " and zbzt = '" + querry.zbzt + "'";
            }

            str += " and xmid not in (select xmid from CProGD)";


            //填过采购的单项  招标申请
            if (!string.IsNullOrEmpty(querry.has))
            {
                //父页面列表
                if (querry.has == "all")
                {
                    //如果没选择就默认 已填报
                    //if ((string.IsNullOrEmpty(querry.Status)))
                    //{
                    //    str = str + " and spstatus != 'unfilled'";
                    //}


                    //如果关联了采购，列表里过滤已经采购完成的
                    var runs = await CProTZJHRule.GetFunGLListBylxEunm(BaseEditPower.JumpModule.采购计划.ToString());
                    if (runs == "1")
                    {
                        str += " and (ISNULL(cgid,'') <> '' or ( ISNULL(zbid,'') <> '') ) ";//ISNULL(cgid,'') = '' and 
                    }
                }
                else//弹窗
                {
                    //选择
                    if ((string.IsNullOrEmpty(querry.Status)))
                    {
                        str = str + " and spstatus == 'unfilled'";
                    }

                    var runs = await CProTZJHRule.GetFunGLListBylxEunm(BaseEditPower.JumpModule.采购计划.ToString());
                    if (runs == "1")
                    {
                        str += " and ISNULL(cgid,'') <> '' and ISNULL(zbid,'') = '' ";
                    }
                    else
                    {
                        str += " and ISNULL(zbid,'') = '' ";
                    }
                }
            }

            //await UserRule.GetUserDepid(uid)
            string sql = "select * from View_ProZBLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str;//Replace("''", "'")

            bool isAsc = false;
            if (querry.sort == "Asc" || querry.sort == "asc")
            {
                isAsc = true;
            }

            if (string.IsNullOrEmpty(querry.column))
            {
                querry.column = " zbid desc,cgid desc,id  ";
            }
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, querry.column, isAsc, querry.size, querry.current);

        }

        //根据id查询单条数据
        public static async Task<dynamic> GetZBByBDId(string keyValue)
        {
            string sql = "select * from View_ProZBLists where id = '" + keyValue + "'";
            return await new RepositoryFactory().BaseRepository().FindEntity(sql, null);
        }
        public static async Task<IEnumerable<dynamic>> GetTBXXByBDId(string zbid)
        {
            string sql = "select * from CProTB where zbid = '" + zbid + "'";
            return await new RepositoryFactory().BaseRepository().FindList(sql, null);
        }

        public static async Task<dynamic> GetZBDWXXByBDId(string dxid)
        {
            //string sql = "select * from CProTB where zbid = '" + zbid + "' and tbdw = (select zbdw from CProZB where id = '" + zbid + "')";

            string sql = "select id,zbid,tbdw dwmc,fddbr drdb,dbr dbry,lxdh,''fddz,''yzbh,shxydm,dbrsfz sfz from CProTB where zbid = (select id from CProZB where dxid = '" + dxid + "' )and tbdw = (select zbdw from CProZB where dxid = '" + dxid + "')";

            return await new RepositoryFactory().BaseRepository().FindList(sql, null);
        }

        #endregion
        //不招标
        public static async Task<bool> InsertCProZBNOTender(List<CProZB> lists, string uid, string strope)
        {
            if (strope == "n")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    for (int i = 0; i < lists.Count; i++)
                    {
                        await irp.Insert(lists[i]);
                    }

                    return true;

                });
            }
            else
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    for (int i = 0; i < lists.Count; i++)
                    {
                        await irp.DeleteAny<CProZB>(new { dxid = lists[i].dxid });
                    }

                    return true;

                });
            }
        }
        //不招标
        public static async Task<bool> InsertCProZBNOTender(CProZB prozb, string uid, string ope)
        {

            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                if (ope == "add")
                {
                    //先删除
                    await irp.DeleteAny<CProZB>(new { dxid = prozb.dxid });
                    //再新增
                    await irp.Insert(prozb);
                }
                else//修改
                {
                    await irp.UpdateAny(prozb, new { dxid = prozb.dxid });
                }

                return true;

            });
        }

        //新增招标
        public static async Task<bool> InsertCProZB(CProZB prozb, List<CProTB> tbs, string uid, string ope)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                if (ope == "add")
                {

                    prozb.createuser = uid;
                    //prozb.status = BaseEditPower.GetSPEnumValue("待提交");
                    prozb.lx = "zb";
                    prozb.zbzt = "1";//填报申请


                    string strsql = "delete from CProTB where zbid in (select id from CProZB where dxid = '" + prozb.dxid + "')";
                    await irp.ExecuteSql(strsql);

                    for (int i = 0; i < tbs.Count; i++)
                    {
                        tbs[i].id = CommonHelper.GetUniqueId().ToString();
                        tbs[i].zbid = prozb.id;

                        await irp.Insert(tbs[i]);
                    }
                    //先删除
                    await irp.DeleteAny<CProZB>(new { dxid = prozb.dxid });
                    //再新增
                    await irp.Insert(prozb);
                }
                else //修改或者中标
                {
                    if (ope == "zb")//中标
                    {
                        prozb.zbzt = "2";//中标状态
                    }

                    if (null != tbs && tbs.Count > 0)
                    {
                        string strsql = "delete from CProTB where zbid in (select id from CProZB where dxid = '" + prozb.dxid + "')";
                        await irp.ExecuteSql(strsql);

                        for (int i = 0; i < tbs.Count; i++)
                        {
                            tbs[i].id = CommonHelper.GetUniqueId().ToString();
                            tbs[i].zbid = prozb.id;
                            await irp.Insert(tbs[i]);
                        }
                    }

                    await irp.UpdateAny(prozb, new { dxid = prozb.dxid }, true);
                }

                return true;

            });

        }

        #region 不用
        //新增修改
        public static async Task InsertCProZBOld(CProZB prozb, string uid)
        {

            CProZB count = await new RepositoryFactory().BaseRepository().FindEntityByKey<CProZB>(prozb.id);
            if (count is null)
            {
                if (string.IsNullOrEmpty(prozb.zbfs))
                {
                    throw new Exception("请选择招标方式");
                }

                //else if (prozb.status == "4")
                //{ 

                //}

                else if (prozb.zbfs == "直接发包")
                {
                    string strid = CommonHelper.GetUniqueId().ToString();
                    prozb.id = strid;
                    prozb.qrr = uid;
                    prozb.createuser = uid;
                    prozb.qrrq = DateTime.Now;
                    prozb.status = "4";//不需招标
                    await new RepositoryFactory().BaseRepository().Insert(prozb);
                }
                else
                {
                    if (string.IsNullOrEmpty(prozb.zbdljg))
                    {
                        throw new Exception("招标代理单位不能为空");
                    }
                    else if (string.IsNullOrEmpty(prozb.bdje.ToString()))
                    {
                        throw new Exception("标底金额不能为空");
                    }
                    else
                    {

                        string strid = CommonHelper.GetUniqueId().ToString();
                        prozb.id = strid;
                        //prozb.status = await GetSFHASHTAsync(prozb.dxid);
                        prozb.status = "3";//确认标底
                        await new RepositoryFactory().BaseRepository().Insert(prozb);
                    }
                }
            }
            else
            {
                await new RepositoryFactory().BaseRepository().Update(prozb);
            }
        }
        #endregion

        public static async Task<string> GetSFHASHTAsync(string dxid)
        {
            string sql = "select * from View_ProZBLists where id = '" + dxid + "'";
            DataTable zBinfo = await new RepositoryFactory().BaseRepository().FindTable(sql, null);
            string str = "";
            for (int i = 0; i < zBinfo.Rows.Count; i++)
            {
                str = zBinfo.Rows[i]["status"].ToString();
            }
            return str;
        }

        //删除多条
        public static async Task<bool> DeleteCProZBMulti(Root ids)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {

                    //string delsql = "delete from CProtB where zbid = '" + idm.id + "'";
                    string delsql = "delete from CProtB where zbid = (select id from CProZB where dxid = '" + idm.id + "')";
                    await irp.ExecuteSql(delsql);

                    //delsql = "delete from CProZB where id = '" + idm.id + "'";
                    delsql = "delete from CProZB where dxid = '" + idm.id + "'";
                    await irp.ExecuteSql(delsql);


                }

                return true;

            });
        }

        //新增投标信息
        public async static Task<int> InsertTBXXMX(CProTB tbr, string strope)
        {
            if (strope == "add")
            {
                return await new RepositoryFactory().BaseRepository().Insert<CProTB>(tbr);
            }
            else if (strope == "edit")
            {
                return await new RepositoryFactory().BaseRepository().Update<CProTB>(tbr);
            }
            else if (strope == "del")
            {
                return await new RepositoryFactory().BaseRepository().Delete<CProTB>(tbr);
            }
            else
                return 0;
        }

        #region 招标代理机构

        public static async Task<(IEnumerable<dynamic>, int)> GetZBDLJGList(ProZBDLJGQuerry querry, string strdepids)//string uid
        {
            string str = "";

            if (!(string.IsNullOrEmpty(querry.xmmc)))
            {
                str = str + " and xmmc like '%" + querry.xmmc + "%'";
            }

            if (!(string.IsNullOrEmpty(querry.dxmc)))
            {
                str = str + " and dxmc like '%" + querry.dxmc + "%'";
            }

            if (!(string.IsNullOrEmpty(querry.status)))
            {
                str = str + " and spstatus = '" + querry.status + "'";
            }

            if (!(string.IsNullOrEmpty(querry.zbdlzt)))
            {
                str = str + " and dljgzt = '" + querry.zbdlzt + "'";
            }
            if (!(string.IsNullOrEmpty(querry.dljgmc)))
            {
                str = str + " and zbdljg like '%" + querry.dljgmc + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.zbdljg)))
            {
                str = str + " and zbdljg like '%" + querry.zbdljg + "%'";
            }
            
            if (!(string.IsNullOrEmpty(querry.sqdw)))
            {
                str = str + " and sqdw = '" + querry.sqdw + "'";
            }
            if (!(string.IsNullOrEmpty(querry.jsdw)))
            {
                str = str + " and buildunit like '%" + querry.jsdw + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.datebeg)))
            {
                str = str + " and sqrq >= '" + querry.datebeg + "'";
            }
            if (!(string.IsNullOrEmpty(querry.dateend)))
            {
                str = str + " and sqrq <= '" + querry.dateend + "'";
            }

            //str += " and dljgzt = '1'";

            str += " and xmid not in (select xmid from CProGD)";


            //await UserRule.GetUserDepid(uid)
            string sql = "select * from View_ProZBDLJGLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str;//Replace("''", "'")

            bool isAsc = false;
            if (querry.sort == "Asc" || querry.sort == "asc")
            {
                isAsc = true;
            }

            if (string.IsNullOrEmpty(querry.column))
            {
                querry.column = "id";
            }
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, querry.column, isAsc, querry.size, querry.current);

        }

        public static async Task<dynamic> GetZBDLJGBydxid(string dxid)
        {
            string sql = "select * from View_ProZBDLJGLists where dxid = '" + dxid + "'";
            return await new RepositoryFactory().BaseRepository().FindEntity(sql, null);
        }

        public static async Task<dynamic> GetZBDLJGByid(string id)
        {
            string sql = "select * from View_ProZBDLJGLists where id = '" + id + "'";
            return await new RepositoryFactory().BaseRepository().FindEntity(sql, null);
        }

        public static async Task<bool> DeleteZBDLJGMulti(Root ids)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    string delsql = "delete from CProZBdljg where id = '" + idm.id + "'";
                    await irp.ExecuteSql(delsql);
                }

                return true;

            });
        }

        public static async Task<bool> InsertZBDLJG(CProZBdljg zbdljg, string strope)
        {
            if (strope == "add")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    await irp.DeleteAny<CProZBdljg>(new { dxid = zbdljg.dxid });

                    await irp.Insert(zbdljg);

                    return true;

                });
            }
            else
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    await irp.Update(zbdljg);

                    return true;

                });
            }
        }


        #endregion

    }
}
